//
//  CarouselView.m
//  itboye_rjy_ios
//
//  Created by pro on 16/1/15.
//  Copyright © 2016年 mc. All rights reserved.
//

#import "CarouselView.h"

// 控制器
#import "ProductDetailsVC.h"
#import "PostDetailVC.h"
#import "WebViewController.h"

// 轮播图片数量
//#define carouselAmount 3

@interface CarouselView () <UIScrollViewDelegate>
{
    NSInteger _carouselAmount;
}
@property (nonatomic, strong) UIScrollView *scrollView; // 滚动视图
@property (nonatomic, strong) UIPageControl *pageControl; // 分页视图
@property (nonatomic, strong) UIActivityIndicatorView *activity; // 菊花

@property (nonatomic, strong) NSTimer *timer; // 定时器

@end

@implementation CarouselView

- (void)dealloc {
    [_timer invalidate];
    _timer = nil;
}

- (instancetype)initWithFrame:(CGRect)frame
                timerDuration:(CGFloat)duration
               carouselAmount:(NSInteger)amount {
    
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
        
        _carouselAmount = amount;
        
        [self _initViews];

        _timer = [NSTimer scheduledTimerWithTimeInterval:duration target:self selector:@selector(_timerAction:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
    
    return self;
}

#pragma mark -- 创建视图 --
- (void)_initViews {
    
    [self _createActivityView];
//    [self _initScrollView];
    [self _createPageControl];
}
// 未加载轮播图片时，先显示菊花转动
- (void)_createActivityView {
    
    _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _activity.center = CGPointMake(self.width / 2, self.height / 2);
    _activity.hidesWhenStopped = YES;
    [self addSubview:_activity];
    [_activity startAnimating];
}
// 创建滚动视图
- (void)_initScrollView {
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];
    _scrollView.contentSize = CGSizeMake(_scrollView.width * (_carouselAmount + 2), _scrollView.height);
    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.delegate = self;
    
    // 为了实现轮播，在需要显示的三个视图前后个在放一个（在第一个视图前面方最后一个视图，在最后一个视图后面方第一个视图）
    UIImageView *first = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _scrollView.width, _scrollView.height)];
    first.image = [UIImage imageWithColor:RED_COLOR];
    first.tag = 10;
    [_scrollView addSubview:first];
    first.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_clickViewAtIndex:)];
    [first addGestureRecognizer:tap];

    // 中间主要显示的视图
    for (int i = 0; i < _carouselAmount; i ++) {
        UIImageView *view = [[UIImageView alloc] initWithFrame:CGRectMake((i+1) * _scrollView.width, 0, _scrollView.width, _scrollView.height)];
        view.image = [UIImage imageWithColor:RED_COLOR];
        view.tag = 11 + i;
        [_scrollView addSubview:view];
        view.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_clickViewAtIndex:)];
        [view addGestureRecognizer:tap2];
    }
    
    UIImageView *final = [[UIImageView alloc] initWithFrame:CGRectMake((_carouselAmount+1) * _scrollView.width, 0, _scrollView.width, _scrollView.height)];
    final.image = [UIImage imageWithColor:RED_COLOR];
    final.tag = 11 + _carouselAmount;
    [_scrollView addSubview:final];
    final.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_clickViewAtIndex:)];
    [final addGestureRecognizer:tap3];
    
    _scrollView.contentOffset = CGPointMake(_scrollView.width, 0);
    
    [self insertSubview:_scrollView atIndex:0];
}

// 创建pageView
- (void)_createPageControl {
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
    _pageControl.backgroundColor = [UIColor clearColor];
    _pageControl.currentPageIndicatorTintColor = RED_COLOR;
    _pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    _pageControl.hidden = YES; // 首先是默认隐藏的
    _pageControl.bottom = self.height - 10;
    _pageControl.center = CGPointMake(SCREEN_WIDTH / 2, _pageControl.center.y);
    [self addSubview:_pageControl];
}

#pragma mark -- 滑动视图代理 --
// 滑动视图已经停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //如果已经滑动到最后一张，则跳到第二张
    if (_scrollView.contentOffset.x == (_carouselAmount+1)*_scrollView.width) {
        _scrollView.contentOffset = CGPointMake(_scrollView.width, 0);
    }
    //如果滑动到到第一张，则跳到倒数第二张
    else if (_scrollView.contentOffset.x == 0) {
        _scrollView.contentOffset = CGPointMake(_carouselAmount * _scrollView.width, 0);
    }
    
    // 设置分页视图的当前页数显示
    NSInteger curPage = _scrollView.contentOffset.x / _scrollView.width - 1;
    _pageControl.currentPage = curPage;
}


#pragma mark -- 定时器方法 --
// 定时器方法
- (void)_timerAction:(NSTimer *)timer {
    // 跳转到下一页
    [UIView animateWithDuration:0.5 animations:^{
        _scrollView.contentOffset = CGPointMake(_scrollView.contentOffset.x + _scrollView.width, 0);
    }];
    //如果已经滑动到最后一张，则跳到第二张
    if (_scrollView.contentOffset.x == (_carouselAmount+1)*_scrollView.width) {
        _scrollView.contentOffset = CGPointMake(_scrollView.width, 0);
    }
    //如果滑动到到第一张，则跳到倒数第二张
    else if (_scrollView.contentOffset.x == 0) {
        _scrollView.contentOffset = CGPointMake(_carouselAmount * _scrollView.width, 0);
    }
    
    // 设置分页视图的当前页数显示
    NSInteger curPage = _scrollView.contentOffset.x / _scrollView.width - 1;
    _pageControl.currentPage = curPage;
}

#pragma mark -- 重写set方法 --
- (void)setModelAry:(NSArray *)modelAry {
    _modelAry = modelAry;

    NSMutableArray *imgUrlStrAry = [[NSMutableArray alloc] init];
    for (CarouselModel *model in modelAry) {
        NSString *urlStr = model.img_url;
        [imgUrlStrAry addObject:urlStr];
    }
    
    self.imgUrlstrAry = imgUrlStrAry;
    
}
- (void)setImgUrlstrAry:(NSArray *)imgUrlstrAry {
    
    // 如果没轮播图，则设置一张默认的图片，且不轮播
    if (imgUrlstrAry == nil || imgUrlstrAry.count == 0) {
        
        imgUrlstrAry = @[@""];
    }
    
    NSMutableArray *tmpAry = [NSMutableArray array];
    tmpAry = [imgUrlstrAry mutableCopy];
    [tmpAry addObject:imgUrlstrAry[0]];
    [tmpAry insertObject:imgUrlstrAry[imgUrlstrAry.count - 1] atIndex:0];
    
    _imgUrlstrAry = [tmpAry copy];
    
    if (_scrollView) {
        [_scrollView removeFromSuperview];
        _scrollView = nil;
    }
    // 设置轮播数量
    _carouselAmount = imgUrlstrAry.count;
    
    [self _initScrollView];
    
    // 显示分页视图
    _pageControl.hidden = NO;
    _pageControl.numberOfPages = _carouselAmount;
    
    // 如果只有一张图片，则不轮播
    if (_carouselAmount == 1) {
        _scrollView.scrollEnabled = NO;
        [_timer invalidate];
        _timer = nil;
        _pageControl.hidden = YES;
    }
    
    // 给轮播图片视图设置从网上获取的图片
    UIImage *placeholderImage = self.isSquare ? DEFAULT_IMAGE : DEFAULT_CAROUSEL_IMAGE;
    for (int tag = 10; tag < 10 + _carouselAmount + 2; tag ++) {
        UIImageView *view = (UIImageView *)[self viewWithTag:tag];
        NSURL *imgUrl = [NSURL URLWithString:_imgUrlstrAry[tag - 10]];
//        __weak UIImageView *w_view = view;
        [view setImageWithURL:imgUrl placeholderImage:placeholderImage completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
            
//            // 在主线程中刷新ui
//            dispatch_async(dispatch_get_main_queue(), ^{
//                // 设置正确的图片尺寸
//                if (image == nil) {
//                    w_view.image = DEFAULT_IMAGE; // 根据宽高比2：1获得图片
//                }
//                w_view.image = [image getCenterImageWithRatio:2]; // 根据宽高比2：1获得图片
//            });
            
        }];
    }
    
    [_activity stopAnimating];
}

- (void)_clickViewAtIndex:(UITapGestureRecognizer *)tap {
    
    NSInteger index = tap.view.tag - 11; // index对应于数据数组中的元素索引
    NSLog(@"数据索引:%li", (long)index);
    CarouselModel *model = _modelAry[index];
    NSLog(@"url_type:%@", model.url_type);
    /*
     6070 链接
     6071 app商品
     6072 app帖子
     */
    switch ([model.url_type integerValue]) {
        case 6070:
        {
            NSLog(@"链接%@",model.url);
            WebViewController *vc = [[WebViewController alloc] initWithUrlString:model.url];
            [self.viewController.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 6071:
        {
            NSLog(@"商品");
            ProductDetailsVC *vc = [[ProductDetailsVC alloc] init];
            vc.pid = model.url;
            [self.viewController.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 6072:
        {
            PostDetailVC *vc = [[PostDetailVC alloc] init];
            vc.tid = model.url;
            [self.viewController.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        default:
            break;
    }
}
@end
